package com.literaryfamily.literaryfamily.myUtil;

import io.micrometer.common.lang.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {
	private static volatile ApplicationContext context;

	@Override
	public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
		// 双重检查确保线程安全
		if (context == null) {
			synchronized (SpringContextUtil.class) {
				if (context == null) {
					context = applicationContext;
				}
			}
		}
	}

	/**
	 * 安全获取Bean（带类型检查）
	 * @param clazz Bean类型
	 * @return Bean实例
	 * @throws IllegalStateException 如果上下文未初始化或Bean不存在
	 */
	public static <T> T getBean(Class<T> clazz) {
		final ApplicationContext ctx = context;
		if (ctx == null) {
			throw new IllegalStateException("Spring上下文未初始化");
		}
		try {
			return ctx.getBean(clazz);
		} catch (NoSuchBeanDefinitionException e) {
			throw new IllegalArgumentException("未找到类型为 " + clazz.getName() + " 的Bean", e);
		}
	}
}